package com.htfyun.ft.fragment.factory;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.htfyun.ft.R;
import com.htfyun.ft.common.FTUtils;
import com.htfyun.ft.myrecorder.IRecordListener;
import com.htfyun.ft.myrecorder.RecorderOperator;
import com.htfyun.ft.utils.DebugLog;

import java.io.File;

import androidx.annotation.Nullable;

public class FragmentSpeaker extends FactoryBaseFragment {

    private MediaPlayer mediaPlayer;
    private AudioManager mAudioManager = null;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_factory_speaker;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {
        super.onInitView(savedInstanceState);

        mAudioManager = (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);

    }

    @Override
    protected void onVisible() {
        super.onVisible();
        initMediaPlayer();
        setBtnEnabled(false);
        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setBtnEnabled(true);
            }
        }, 4000);
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        deinitMediaPlayer();
    }

    private void setBtnEnabled(boolean enabled) {
        setBtnPassEnabled(enabled);
        setBtnFailEnabled(enabled);
    }

    private void initMediaPlayer() {

        if (mediaPlayer != null) {
            deinitMediaPlayer();
        }
        mediaPlayer = MediaPlayer.create(getContext(), R.raw.music_test_channel);
        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        DebugLog.e("currentVolume: " + currentVolume + " maxVolume: " + maxVolume);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,maxVolume,0);
        mediaPlayer.start();//开始音频的播放
        mediaPlayer.setLooping(true);
    }

    private void deinitMediaPlayer() {
        if(mediaPlayer !=null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

}
